package io.github.qifan777.server.wallet.root.controller;

import cn.dev33.satoken.stp.StpUtil;
import io.github.qifan777.server.Immutables;
import io.github.qifan777.server.user.root.event.UserEvent;
import io.github.qifan777.server.wallet.root.entity.Wallet;
import io.github.qifan777.server.wallet.root.repository.WalletRepository;
import io.qifan.infrastructure.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import org.babyfish.jimmer.client.FetchBy;
import org.babyfish.jimmer.client.meta.DefaultFetcherOwner;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@RequestMapping("front/wallet")
@AllArgsConstructor
@DefaultFetcherOwner(WalletRepository.class)
@Transactional
public class WalletForFrontController {
    private final WalletRepository walletRepository;

    @GetMapping
    public @FetchBy(value = "COMPLEX_FETCHER_FOR_FRONT") Wallet wallet() {
        return walletRepository.findById(StpUtil.getLoginIdAsString())
                .orElseThrow(() -> new BusinessException("钱包不存在"));
    }

    @EventListener
    public void onUserCreatedEvent(UserEvent.UserCreateEvent userCreateEvent) {
        walletRepository.insert(Immutables.createWallet(draft -> {
            draft
                    .setUserId(userCreateEvent.userId())
                    .setBalance(BigDecimal.ZERO)
                    .setId(userCreateEvent.userId());
        }));
    }
}
